<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/about' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card style="margin-top: 20px">
      <!-- 警句 -->
      <el-alert
        class="el-icon-info"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
      >
      </el-alert>
      <!-- 输入框 -->
      <span style="margin-top: 20px">选择商品分类：</span>
      <el-cascader
        v-model="defKeys"
        :options="cateList"
        :props="props"
        @change="handleChange"
        style="margin-top: 20px"
        placeholder="请选择活动区域"
      >
      </el-cascader>
      <!-- 静态参数     动态参数 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 动态 -->
          <el-row>
            <el-col :span="6">
              <el-button
                type="primary"
                :disabled="disabled"
                size="small"
                @click="add"
                plain
                >添加参数</el-button
              >
            </el-col>
            <el-table :data="paramList" border="">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <div>
                    <el-tag
                      :key="i"
                      style=""
                      v-for="(item, i) in scope.row.attr_vals"
                      :disable-transitions="false"
                      closable
                      @close="handleClose(scope.row, i)"
                      >{{ item }}</el-tag
                    >
                    <!-- 添加tag -->
                    <el-input
                      style="margin-left: 10px"
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      style="margin-left: 10px"
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </div>
                </template>
              </el-table-column>
              <el-table-column type="index"></el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称"
              ></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="small" @click="handleEdit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-tab-pane>

        <!-- 静态 -->
        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-col :span="6">
              <el-button
                type="primary"
                :disabled="disabled"
                size="small"
                @click="add"
                plain
                >添加属性</el-button
              >
            </el-col>
            <el-table :data="paramList" border="">
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <div>
                    <el-tag
                      :key="i"
                      style=""
                      v-for="(item, i) in scope.row.attr_vals"
                      :disable-transitions="false"
                      closable
                      @close="handleClose(scope.row, i)"
                      >{{ item }}</el-tag
                    >
                    <!-- 添加tag -->
                    <el-input
                      style="margin-left: 10px"
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveTagInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button
                      v-else
                      style="margin-left: 10px"
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                      >+ New Tag</el-button
                    >
                  </div>
                </template>
              </el-table-column>
              <el-table-column type="index"></el-table-column>
              <el-table-column
                prop="attr_name"
                label="属性名称"
              ></el-table-column>  
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    @click="handleEdit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleDelete( scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数 的弹框 -->
    <el-dialog title="添加动态参数" :visible.sync="dialogFormVisible">
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="ruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑动态参数 的弹框 -->
    <el-dialog title="编辑参数" :visible.sync="dialogFormVisible1">
      <el-form
        :model="ruleForm1"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="动态参数" prop="attr_name">
          <el-input v-model="ruleForm1.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="submitForm1">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "params",
  data() {
    return {
      // 添加tag
      // inputVisible: false,
      // inputValue: "",
      // 级联选择器相关
      defKeys: [],
      cateList: [],
      props: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      activeName: "many",
      //   参数列表相关
      paramList: [],
      //  添加动态参数的弹框
      dialogFormVisible: false,
      ruleForm: {
        attr_name: "",
      },
      rules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      //  编辑动态参数的弹框
      dialogFormVisible1: false,
      ruleForm1: {
        attr_name: "",
      },
    };
  },
  mounted() {
    this.getdata();
  },
  computed: {
    disabled() {
      if (this.defKeys.length == 3) {
        return false;
      } else {
        return true;
      }
    },
  },
  methods: {
    // 编辑
    handleEdit(row) {
      console.log(row);
      this.dialogFormVisible1 = true;
      this.ruleForm1 = row;
    },
    //   编辑的接口
    async submitForm1() {
      let result = await this.$axios({
        url: `api/private/v1/categories/${this.defKeys[2]}/attributes/${this.ruleForm1.attr_id}`,
        method: "PUT",
        data: {
          attr_name: this.ruleForm1.attr_name,
          attr_sel: this.activeName, 
        },
      });
      console.log(result, "编辑参数");
      if (result.data.meta.status !== 200)
        return this.$message.error(result.data.meta.msg);
      this.dialogFormVisible1 = false;
      this.$message.success(result.data.meta.msg);
      this.getdata();
    },
    // 删除参数
    handleDelete(row) {
      console.log(row); 
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          var res = await this.$axios({
            url: `/api/private/v1/categories/${this.defKeys[2]}/attributes/${row.attr_id}`,
            method: "delete",
          });
          console.log(res, "删除参数");
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.handleChange();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 显示tag的输入框
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 添加tag
    async handleInputConfirm(row) {
      let inputValue = row.inputValue;
      row.inputVisible = false;
      if (!inputValue) return;
      row.attr_vals.push(inputValue);
      row.inputValue = "";

      // 请求接口
      let { data: res } = await this.$axios({
        url: `/api/private/v1/categories/${this.defKeys[2]}/attributes/${row.attr_id}`,
        method: "put",
        data: {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(" "),
        },
      });
      console.log(res, "添加动态");
      this.getdata();
    },

    // 删除tag
    async handleClose(row, i) {
      console.log(row);
      // 删除页面的tag
      row.attr_vals.splice(i, 1);
      // 删除数据库中的tag
      let { data: res } = await this.$axios({
        url: `/api/private/v1/categories/${this.defKeys[2]}/attributes/${row.attr_id}`,
        method: "PUT",
        data: {
          attr_name: row.attr_name,
          attr_vals: row.attr_vals.join(" "),  //  数组join转字符串
          attr_sel: this.activeName,
        },
      }).catch((err) => err);
      console.log(res);
      this.getdata();
    },
    // 添加动态参数请求接口
    async submitForm() {
      let { data: res } = await this.$axios({
        url: `/api/private/v1/categories/${this.defKeys[2]}/attributes`,
        method: "post",
        data: {
          attr_name: this.ruleForm.attr_name,
          attr_sel: this.activeName,
        },
      });
      console.log(res, "添加动态");
      this.dialogFormVisible = false;
      this.ruleForm = {};
      this.handleChange();
    },
    // 添加动态参数
    add() {
      this.dialogFormVisible = true;
    },
    // 渲染
    async getdata() {
      let { data: res } = await this.$axios({
        url: "/api/private/v1/categories",
        method: "GET",
        params: {
          type: 3,
        },
      }).catch((err) => err);
      console.log(res, "categories渲染oo");
      if (res.meta.status !== 200) return this.$message.error("数据请求错误");
      this.cateList = res.data;
      this.total = res.data.total;
    },
    // 获取动态参数或静态属性列表
    async handleChange() {
      if (this.defKeys.length !== 3) {
        return;
      }
      this.getdata();

      // 获取某分类下的参数列表
      let { data: res } = await this.$axios({
        url: `/api/private/v1/categories/${this.defKeys[2]}/attributes`,
        method: "GET",
        params: {
          sel: this.activeName,
        },
      }).catch((err) => err);
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("参数请求错误");
      //   字符串转数组
      res.data.forEach((item) => {
        item.inputValue = "";
        item.inputVisible = false;
        if (item.attr_vals === "") {
          item.attr_vals = [];
        } else {
          item.attr_vals = item.attr_vals.split(" ");
        }
      });
      this.paramList = res.data;
    },

    tabClick() {
      this.handleChange();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 0 8px;
}
.input-new-tag {
  width: 30px;
}
.tag_container {
  width: 90%;
  margin: 0 auto;
}
</style>
